package com.cet.algorithm.哈希表;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: algorithm
 * @description: 字母异位词分组
 * @author: 陈恩涛
 * @create: 2022-03-13 13:47
 **/
public class LC49 {

    /**
     * 错误，存在hash冲突，但方向是对的
     * @param strs
     * @return
     */
    /*public static List<List<String>> groupAnagrams(String[] strs) {
        Map<Integer, List<String>> map = new HashMap<>();
        for (String str : strs) {
            int hash = 0;
            for (int i = 0; i < str.length(); i++) {
                hash += str.charAt(i) - 'a';
            }
            if (map.get(hash) == null) {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(hash, list);
            } else {
                map.get(hash).add(str);
            }
        }
        List<List<String>> result = new ArrayList<>();
        result.addAll(map.values());
        return result;
    }*/

    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            int[] alphabetCounter = new int[26];
            for (int i = 0; i < str.length(); i++) {
                alphabetCounter[str.charAt(i) - 'a']++;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < alphabetCounter.length; i++) {
                while (alphabetCounter[i] != 0) {
                    sb.append((char)('a' + i));
                    alphabetCounter[i]--;
                }
            }
            List<String> list = map.getOrDefault(sb.toString(), new ArrayList<>());
            list.add(str);
            map.put(sb.toString(), list);
        }
        return new ArrayList<>(map.values());
    }

    public static void main(String[] args) {
    }
}
